<template>
  <div class="carriaGe-container">
    <!-- 头部 -->
    <div class="head-container">
      <el-card class="box-card">
        <span style="margin: 0 50px 0 20px; font-size: 14px">
          车辆类型：<el-select
            v-model="truckTypeId"
            placeholder="请选择"
            style="width: 280px"
          >
            <el-option
              v-for="item in CarTypeList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
            <!--  -->
          </el-select>
        </span>

        <span style="margin: 0 50px 0 10px; font-size: 14px">
          车牌号码：<el-input
            v-model="licensePlate"
            style="width: 280px"
            placeholder="请输入车牌号码"
          />
        </span>

        <el-button
          type="primary"
          style="
            background-color: #e15536;
            border: none;
            width: 90px;
            height: 40px;
          "
          @click="search"
        >
          <span>搜索</span>
        </el-button>
        <el-button
          plain
          style="
            border: 1px solid #999;
            width: 90px;
            height: 36px;
            transform: translateY(1px);
          "
          @click="reset"
        >
          <span>重置</span>
        </el-button>
      </el-card>
    </div>

    <!-- 导航栏 -->
    <el-menu
      class="el-menu-demo"
      mode="horizontal"
      background-color="#fff"
      text-color="#e15536"
      active-text-color="#de1d0a"
      default-active="1"
    >
      <el-menu-item
        style="width: 120px; text-align: center"
        index="1"
        @click="getVehicle"
      >全部{{ total }}</el-menu-item>
      <el-menu-item
        style="width: 120px; text-align: center"
        index="2"
        @click="getWorkingTrucks"
      >可用{{ Working }}</el-menu-item>
      <el-menu-item
        style="width: 120px; text-align: center"
        index="3"
        @click="getUnWorkingTrucks"
      >停用{{ unWorking }}</el-menu-item>
    </el-menu>

    <!-- 内容 -->
    <!-- 表格 -->
    <div class="car-models">
      <el-card class="box-card">
        <el-button
          type="primary"
          style="background-color: #e15536; border: none"
          @click="addVehicle"
        >
          新增车辆
        </el-button>
        <el-table
          :data="list"
          show-header
          style="
            width: 1300px;
            margin-bottom: 10px;
            border: 1px solid #ebeef5;
            margin-top: 20px;
            color: #20232a;
            font-size: 13px;
          "
          :header-cell-style="{ background: '#f8faff' }"
        >
          <!-- 序号 -->
          <el-table-column align="left" width="60" type="index" label="序号" />

          <!-- 车牌号码 -->
          <el-table-column
            align="left"
            width="115"
            label="车牌号码"
            prop="licensePlate"
          />

          <!-- 车辆类型 -->
          <el-table-column
            align="left"
            prop="truckTypeName"
            width="111"
            label="车辆类型"
          />

          <!-- 司机数量 -->
          <el-table-column
            align="left"
            prop="driverNum"
            width="111"
            label="司机数量"
          />

          <!-- 车辆状态 -->
          <el-table-column
            align="left"
            prop="status"
            width="111"
            label="车辆状态"
          >
            <template v-slot="{ row }">
              <span v-if="row.workStatus === 1">
                <i class="status-point" style="background-color: #67c23a" />可用
              </span>
              <span v-else-if="row.workStatus===0">
                <i class="status-point" style="background-color: #ff0000" />停用
              </span>
            </template>
          </el-table-column>

          <!-- GPS设备ID -->
          <el-table-column
            align="left"
            prop="deviceGpsId"
            width="167"
            label="GPS设备ID"
          >
            <!-- <template v-slot="{ row }">
                <span>{{ row.name }}</span>
              </template> -->
          </el-table-column>

          <!-- 实载重量 -->
          <el-table-column
            align="left"
            prop="allowableLoad"
            width="167"
            label="实载重量(T)"
          />

          <!-- 实载体积(方) -->
          <el-table-column
            align="left"
            prop="allowableVolume"
            width="167"
            label="实载体积(方)"
          />

          <!-- 操作 -->
          <el-table-column align="center" label="操作">
            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click="carDetail(row)">查看详情</el-button>
              <span style="margin: 0 5px 0 5px; color: #c1c1c1">|</span>
              <el-button
                v-if="row.status===0"
                size="mini"
                type="text"
                style="color: red"
                @click="stopApply(row.id)"
              >停用</el-button>
              <el-button
                v-else-if="row.status===1"
                size="mini"
                type="text"
                @click="enable(row.id)"
              >启用</el-button>
              <span style="margin: 0 5px 0 5px; color: #c1c1c1">|</span>
              <el-button size="mini" type="text" @click="configDriver(row.id)">配置司机</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
          align="center"
          :current-page="page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>
    <!-- 对话框 -->
    <el-dialog :title="`新增车辆`" :visible.sync="showDialog" width="600px" @close="btnCancel">
      <el-row type="flex" justify="center">
        <el-form
          ref="CarForm"
          size="small"
          label-position="right"
          label-width="80px"
          :model="CarForm"
          :rules="rules"
        >
          <el-form-item prop="truckTypeId" label="车辆类型">
            <el-select
              v-model="CarForm.truckTypeId"
              placeholder="请选择"
              style="width: 420px"
            >
              <el-option
                v-for="item in CarTypeList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item prop="licensePlate" label="车牌号码">
            <el-input
              v-model="CarForm.licensePlate"
              placeholder="请输入车牌号码"
              autocomplete="off"
              style="width: 420px"
            />
          </el-form-item>

          <el-form-item prop="deviceGpsId" label="GPS设备ID" class="GPS">
            <el-input
              v-model="CarForm.deviceGpsId"
              placeholder="请输入GPS设备ID"
              autocomplete="off"
              style="width: 420px"
            />
          </el-form-item>

        </el-form>
      </el-row>

      <div slot="footer" class="dialog-footer" style="transform: translateY(-30px);">
        <el-row type="flex" justify="center">
          <el-button type="primary" size="medium" style="width:90px ; background-color: #e15536; border: none;" @click="btnOK">确 定</el-button>
          <el-button size="medium " style="width:90px ;" @click="btnCancel">取 消</el-button>
        </el-row>
      </div>
    </el-dialog>

    <!-- 配置司机 对话框 -->
    <el-dialog title="配置司机" :visible.sync="visible">

      <div class="header">
        <div>
          <span>车牌号：</span>
          <span class="header-text">{{ Driver.licensePlate }}</span>
        </div>
        <div>
          <span>车型：</span>
          <span class="header-text">{{ Driver.truckTypeName }}</span>
        </div>
        <div>
          <span>车辆状态：</span>
          <span v-if="Driver.status===1" class="header-text" style="background-color:#37c608; border-radius: 8px;">可用</span>
          <span v-else class="header-text">停用</span>
        </div>
        <div>
          <span>实载重量：</span>
          <span class="header-text">{{ Driver.allowableLoad }}</span>
        </div>
        <div>
          <span>实载体积：</span>
          <span class="header-text">{{ Driver.allowableVolume }}</span>
        </div>
      </div>

      <div class="serBox">
        <label>配置司机：</label>
        <el-select
          v-model="selectCar"
          suffix-icon="el-icon-search"
          placeholder="请输入配置司机"
          filterable
          @change="handleChange"
        >
          <el-option
            v-for="item in carList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </div>

      <el-table align="center">
        visible
        <el-table-column label="车牌号" width="150">
          <template v-slot="{row}">
            {{ row.licensePlate }}
          </template>data
        </el-table-column>
        <el-table-column label="车辆状态" width="200">
          {{ '可用'|| '停用' }}
        </el-table-column>
        <el-table-column label="操作">

          <el-link
            type="primary"
            :underline="false"
          >查看</el-link>
          <!-- @click="$router.push(`/expreManagement/carDetail/${row}`)" -->
          <el-divider direction="vertical" />
          <el-link
            type="danger"
            :underline="false"
          >删除</el-link>

        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary">提交</el-button>
      </span>

    </el-dialog>
    <!-- 查看详情组件
    <VehicleDetail /> -->
  </div>
</template>

<script>
import { addVehicle, editDisable, editEnable, getUnWorkingTrucks, getVehicle, getVehicleDetail, getWorkingTrucks } from '@/api/vehicle'
// import VehicleDetail from './components/VehicleDetail.vue'
export default {
  name: 'CheHangList',
  // components: {
  //   VehicleDetail
  // },
  data() {
    return {
      // id: null, // 跳转详情id
      visible: false,
      showDialog: false,
      list: [],
      options: [], // 车型下拉框
      page: 1, // 当前页面
      pageSize: 10, // 页大小
      total: 0, // 总页数
      Working: 0, // 可用车辆总数
      unWorking: 0, // 停用车辆总数
      CarTypeList: [], // 车辆类型下拉菜单
      truckTypeId: '', // 车辆类型id
      licensePlate: '', // 车牌号码
      // 新增车辆对象
      CarForm: {
        truckTypeId: null, // 车型id
        licensePlate: '', // 车牌号码
        deviceGpsId: '' // GPS设备id
      },
      // 配置司机对象
      Driver: {},
      carList: [], // 配置司机下拉数组
      selectCar: '',
      // 表单校验
      rules: {
        truckTypeId: [
          // 车型id
          { required: true, message: '车辆类型不能为空', trigger: 'blur' }
          // { type: 'number', message: '必须为数字值', trigger: 'blur' }
        ],
        licensePlate: [{ required: true, message: '车牌号码不能为空', trigger: 'blur' },
          { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/, message: '车牌格式不对' },
          {
            trigger: 'blur',
            // 自定义校验模式
            validator: async(rule, value, callback) => {
              // value就是输入的编码
              const res = await getVehicle({ page: this.page, pageSize: this.pageSize })
              // console.log(res.items)
              // result数组中是否存在 value值
              if (res.items.some((item) => item.licensePlate === value)) { // 新增
              // if (res.items.some((item) => item.licensePlate === value && this.carTypeForm.id !== item.id)) { // 编辑
                callback(new Error('车牌号码已存在'))
              } else {
                callback()
              }
            }
          }],
        deviceGpsId: [
          // GPS设备id
          { required: true, message: 'GPS设备ID不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getVehicle()
    this.selectList()
  },
  methods: {
    // 获取分页数据  全部数据
    async getVehicle() {
      const res = await getVehicle({ page: this.page, pageSize: this.pageSize })
      // console.log(res.items)
      this.list = res.items
      this.page = res.page
      this.pageSize = res.pageSize
      this.total = res.items.length

      // 可用车辆
      const resWorking = await getWorkingTrucks()
      // console.log(res)
      this.Working = resWorking.length
      // 停用车辆
      const resunWorking = await getUnWorkingTrucks()
      this.unWorking = resunWorking.length
    },
    // 车辆类型下拉菜单  数据去重
    async selectList() {
      const res = await getVehicle({ page: this.page, pageSize: this.pageSize })
      const list = []
      res.items.forEach(ele => list.push({ name: ele.truckTypeName, value: ele.truckTypeId }))
      list.reduce((accumulator, currentItem) => {
        const existingItem = accumulator.find(item => item.value === currentItem.value)
        if (!existingItem) {
          accumulator.push(currentItem)
        }
        return accumulator
      }, this.CarTypeList)
    },
    // 获取可用车辆
    async getWorkingTrucks() {
      const res = await getWorkingTrucks()
      this.Working = res.length
      this.list = res
    },
    // 获取停用车辆
    async getUnWorkingTrucks() {
      const res = await getUnWorkingTrucks()
      this.list = res
    },
    // 分页
    // 每页大小改变触发
    handleSizeChange(newPageSize) {
      this.pageSize = newPageSize
      this.getVehicle()
    },
    // 当前页改变触发
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getVehicle()
    },
    // 搜索
    async search() {
      const res = await getVehicle({ page: this.page, pageSize: this.pageSize, truckTypeId: this.truckTypeId, licensePlate: this.licensePlate })
      // console.log(res)
      this.total = parseInt(res.items.length) // 数据更新 总页码也要更新
      this.page = res.page // 数据更新 页码也要更新
      this.pageSize = res.pageSize // 数据更新 页大小也要更新
      this.list = res.items // 更新表格数据
    },
    // 搜索重置
    reset() {
      this.truckTypeId = ''
      this.licensePlate = ''
      this.search()
    },
    // 新增车辆
    addVehicle() {
      this.showDialog = true
      this.selectList() // 重新获取车型数据 确保数据是最新的
    },
    // 表单确定
    async btnOK() {
      await this.$refs.CarForm.validate()
      await addVehicle(this.CarForm)
      this.$message.success('操作成功')
      this.$refs.CarForm.resetFields()
      this.showDialog = false
      this.getVehicle()
    },
    // 表单取消
    btnCancel() {
      this.$refs.carTypeForm.resetFields()
      this.showDialog = false
      setTimeout(() => {
        this.carTypeForm.id = null
      }, 500)
    },
    // 停用
    stopApply(id) {
      this.$confirm('确定要停用吗？车辆停用需满足以下条件：  1车辆当前无运输任务   2车辆无关联运输线路' + '注：停用后司机将自动解除绑定', '车辆停用', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await editDisable(id)
        this.$message({
          type: 'success',
          message: '操作成功'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 启用
    async enable(id) {
      // console.log(id)
      const res = await editEnable(id)
      console.log(res)
      if (res.status === 200) {
        this.$message.error(res.data.msg)
      } else {
        this.$message.success(res.data.msg)
      }
    },
    // 配置司机
    async configDriver(id) {
      this.$confirm('配置车辆需满足以下条件：\n1. 司机信息已完善\n2. 司机已设置排班\n3. 司机绑定车辆未在启用状态',
        '车辆配置', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
        const res = await getVehicleDetail(id) // 获取车辆信息
        this.Driver = res
        this.visible = true // 控制对话框的显示
      }).catch(() => {
        // 取消按钮的回调
      })
    },
    // 配置司机-取消
    handleChange() {

    },
    carDetail(row) {
      this.$router.push({
        name: '/expreManagement/carDetail',
        params: {
          myObject: row
        }
      })
    }

  }
}
</script>

<style lang='scss'  >
.el-form-item .el-form-item__label{
    // color: red !important;
    color: #000;
    font-size: 14px !important;
    font-weight: normal !important;
  }
.carriaGe-container {
  padding-left: 20px;
  padding-right: 20px;
  background-color: #f4f6f8;

  .head-container {
    .box-card {
      margin-bottom: 20px;

      // .serial-number {
      // }
      // .weight {
      // }
      // .bulk {
      // }
      // .car-type {
      // }
    }
  }
  .car-models {
    .box-card {
      margin-top: 20px;
      .status-point {
        display: inline-block;
        width: 6px;
        height: 6px;
        border-radius: 50%;
        margin-right: 5px;
        transform: translateY(-1.5px);
      }
    }
    .text {
      font-size: 14px;
    }
  }
}
</style>

